#include <jni.h>
#include <string>

#include "RtmpHelper.h"
#include "X264Helper.h"

#include "log.h"

RtmpHelper *rtmpHelper = nullptr;
JavaCallHelper *javaCallHelper = nullptr;
X264Helper *x264Helper = nullptr;

//虚拟机的引用
JavaVM *javaVM = nullptr;
// jni初始化的方法
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
    javaVM = vm;
    LOGE("JNI_OnLoad");
    return JNI_VERSION_1_4;
}

// RTMP连接
extern "C"
JNIEXPORT jboolean JNICALL
Java_com_yjz_media_study_rtmp_RTMPNativeHelper_connectRTMP(JNIEnv *env, jobject thiz, jstring url) {
    rtmpHelper = new RtmpHelper;
    char *_url = const_cast<char *>(env->GetStringUTFChars(url, nullptr));
    int ret = rtmpHelper->connect(_url);
    env->ReleaseStringUTFChars(url, _url);
    return ret;
}

// 发送数据给rtmp
extern "C"
JNIEXPORT void JNICALL
Java_com_yjz_media_study_rtmp_RTMPNativeHelper_sendData(JNIEnv *env, jobject thiz, jbyteArray buffer, jint length, jint type) {
    jbyte *data = env->GetByteArrayElements(buffer, nullptr);
    rtmpHelper->sendData(data, length, type);
    env->ReleaseByteArrayElements(buffer, data, 0);
}

// 断开连接
extern "C"
JNIEXPORT void JNICALL
Java_com_yjz_media_study_rtmp_RTMPNativeHelper_disconnect(JNIEnv *env, jobject thiz) {
    rtmpHelper->disconnect();
}

// x264初始化
extern "C"
JNIEXPORT jboolean JNICALL
Java_com_yjz_media_study_jni_X264NativeHelper_init(JNIEnv *env, jobject thiz, jint width, jint height, jint fps, jint bitrate) {
    LOGE("Java_com_yjz_media_study_jni_X264NativeHelper_ini1");
    javaCallHelper = new JavaCallHelper(javaVM, env, thiz);
    x264Helper = new X264Helper();
    x264Helper->javaCallHelper = javaCallHelper;
    x264Helper->rtmpHelper = rtmpHelper;
    int ret = x264Helper->setVideoEncInfo(width, height, fps, bitrate);
    return ret;
}

// x264编码
extern "C"
JNIEXPORT void JNICALL
Java_com_yjz_media_study_jni_X264NativeHelper_encodeData(JNIEnv *env, jobject thiz, jbyteArray buffer, jint length, jint type) {
    if (!x264Helper) {
        return;
    }
    jbyte *data = env->GetByteArrayElements(buffer, nullptr);
    x264Helper->encodeData(data, length, type);
    env->ReleaseByteArrayElements(buffer, data, 0);
}